package com.example.myapplication.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myapplication.data.model.StorageSpace
import com.example.myapplication.data.model.StorageSpaceWithCount
import com.example.myapplication.data.repository.StorageSpaceRepository
import com.example.myapplication.data.repository.StorageItemRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject

/**
 * 主屏幕UI状态
 */
data class MainUiState(
    val isLoading: Boolean = false,
    val storageSpaces: List<StorageSpaceWithCount> = emptyList(),
    val errorMessage: String? = null,
    val successMessage: String? = null, // 新增：操作成功消息
    // 新增：删除确认状态
    val spaceToDelete: StorageSpace? = null,
    val deleteConfirmationInfo: String? = null
)

/**
 * 储物空间及其物品数量
 */
data class StorageSpaceWithCount(
    val space: StorageSpace,
    val itemCount: Int
)

/**
 * 主屏幕ViewModel
 */
@HiltViewModel
class MainViewModel @Inject constructor(
    private val storageSpaceRepository: StorageSpaceRepository,
    private val storageItemRepository: StorageItemRepository
) : ViewModel() {

    private val _uiState = MutableStateFlow(MainUiState())
    val uiState: StateFlow<MainUiState> = _uiState.asStateFlow()

    init {
        loadTopLevelSpaces()
    }

    /**
     * 加载顶级储物空间
     */
    private fun loadTopLevelSpaces() {
        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true, errorMessage = null)
            
            try {
                storageSpaceRepository.getTopLevelSpacesWithCounts()
                    .collect { spacesWithCount ->
                        _uiState.value = _uiState.value.copy(
                            isLoading = false,
                            storageSpaces = spacesWithCount,
                            errorMessage = null
                        )
                    }
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    isLoading = false,
                    errorMessage = "加载储物空间失败: ${e.message}"
                )
            }
        }
    }

    /**
     * 添加新的储物空间
     */
    fun addStorageSpace(name: String, description: String?, iconType: String?) {
        viewModelScope.launch {
            try {
                val newSpace = StorageSpace(
                    name = name,
                    description = description,
                    iconType = iconType
                )
                storageSpaceRepository.insertOrUpdateSpace(newSpace)
                _uiState.value = _uiState.value.copy(
                    successMessage = "储物空间 '${name}' 添加成功"
                )
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    errorMessage = "添加储物空间失败: ${e.message}"
                )
            }
        }
    }

    fun updateSpace(spaceId: String, name: String, description: String?, iconType: String?) {
        viewModelScope.launch {
            try {
                val space = storageSpaceRepository.getSpaceById(spaceId)
                if (space != null) {
                    val updatedSpace = space.copy(
                        name = name,
                        description = description,
                        iconType = iconType
                    )
                    storageSpaceRepository.insertOrUpdateSpace(updatedSpace)
                    _uiState.value = _uiState.value.copy(
                        successMessage = "储物空间 '${name}' 更新成功"
                    )
                }
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(errorMessage = "更新空间失败: ${e.message}")
            }
        }
    }

    /**
     * 删除储物空间
     */
    fun deleteStorageSpace(spaceId: String) {
        viewModelScope.launch {
            try {
                // 先获取空间信息
                val space = storageSpaceRepository.getSpaceById(spaceId)
                if (space == null) {
                    _uiState.value = _uiState.value.copy(errorMessage = "找不到要删除的空间")
                    return@launch
                }
                
                // 检查空间内容
                val hasChildren = storageSpaceRepository.hasChildSpaces(spaceId)
                val itemCount = storageSpaceRepository.getItemCount(spaceId)
                
                if (hasChildren || itemCount > 0) {
                    // 有内容时显示确认对话框
                    val confirmationInfo = buildString {
                        append("删除空间 '${space.name}' 将同时删除：\n")
                        if (hasChildren) append("• 所有子空间\n")
                        if (itemCount > 0) append("• ${itemCount}个物品\n")
                        append("\n此操作无法撤销，确定要继续吗？")
                    }
                    _uiState.value = _uiState.value.copy(
                        spaceToDelete = space,
                        deleteConfirmationInfo = confirmationInfo
                    )
                } else {
                    // 空间为空，直接删除
                    performSpaceDeletion(space)
                }
            } catch (e: Exception) {
                _uiState.value = _uiState.value.copy(
                    errorMessage = "检查空间状态失败: ${e.message}"
                )
            }
        }
    }

    /**
     * 执行空间删除
     */
    private suspend fun performSpaceDeletion(space: StorageSpace) {
        try {
            storageSpaceRepository.deleteSpaceById(space.id)
            _uiState.value = _uiState.value.copy(
                successMessage = "储物空间 '${space.name}' 删除成功"
            )
        } catch (e: Exception) {
            _uiState.value = _uiState.value.copy(
                errorMessage = "删除储物空间失败: ${e.message}"
            )
        }
    }

    /**
     * 确认删除空间
     */
    fun confirmSpaceDeletion() {
        val spaceToDelete = _uiState.value.spaceToDelete
        if (spaceToDelete != null) {
            viewModelScope.launch {
                performSpaceDeletion(spaceToDelete)
                _uiState.value = _uiState.value.copy(
                    spaceToDelete = null,
                    deleteConfirmationInfo = null
                )
            }
        }
    }

    /**
     * 取消删除空间
     */
    fun cancelSpaceDeletion() {
        _uiState.value = _uiState.value.copy(
            spaceToDelete = null,
            deleteConfirmationInfo = null
        )
    }

    /**
     * 清除错误消息
     */
    fun clearErrorMessage() {
        _uiState.value = _uiState.value.copy(errorMessage = null)
    }

    /**
     * 清除成功消息
     */
    fun clearSuccessMessage() {
        _uiState.value = _uiState.value.copy(successMessage = null)
    }

    /**
     * 刷新数据
     */
    fun refresh() {
        loadTopLevelSpaces()
    }
} 